<?php
/**
 * @file tags.php
 * @author CaoQiCheng
 * @date 2017年2月8日 下午17:05:11
 * @brief 
 */
namespace haibao\jiepai\data;


class Goods extends \haibao\jiepai\data\BaseMysql{	
	public function __construct(){
		parent::__construct('\haibao\jiepai\model\data\goods\CmsGoods');
	}
	
	public function saveGoods($goodsModel,$tagArr,$goodsPicture,$stylePicture){
		$this->beginTranscation();
		try {
			if($goodsModel->Id){
				$this->save($goodsModel);
			}else {
				$this->add($goodsModel);
			}
			 
			$this->saveGoodsTags($goodsModel->Id, $tagArr);
			$this->savaGoodsPicture($goodsModel->Id, $goodsPicture,$stylePicture);
		
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function saveGoodsTags($goodsId,$tagArr){
		if(!$goodsId){
			return false;
		}
		if(!$tagArr){
			return false;
		}
		$this->query('delete from `cms_goods_tags` where GoodsID = %s', array(
				$goodsId
		));
		if(isset($tagArr) && $tagArr){
			$sql = 'insert into cms_goods_tags(GoodsID,TagID) values ';
			$arrSql = $arrValues = array();
			foreach($tagArr as $key=>$val){
				array_push($arrSql, '(%s,%s)');
				array_push($arrValues, $goodsId);
				array_push($arrValues, $val);
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		}
		
	}
	
	public function savaGoodsPicture($goodsId,$goodsPictureIds,$stylePictureIds){
		if(!$goodsId){
			return false;
		}
		$this->query('delete from `cms_goods_pictures` where GoodsID = %s', array(
				$goodsId
		));
		if(isset($goodsPictureIds) && $goodsPictureIds){
			$sql = 'insert into cms_goods_pictures(Type,GoodsID,FileID,ShowIndex) values ';
			$arrSql = $arrValues = array();
			foreach($goodsPictureIds as $key=>$val){
				array_push($arrSql, '(%s,%s,%s,%s)');
				array_push($arrValues, 1);
				array_push($arrValues, $goodsId);
				array_push($arrValues, $val);
				array_push($arrValues, $key);
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		}
		
		if(isset($stylePictureIds) && $stylePictureIds){
			$sql1 = 'insert into cms_goods_pictures(Type,GoodsID,FileID,ShowIndex) values ';
			$arrSql1 = $arrValues1 = array();
			foreach($stylePictureIds as $key=>$val){
				array_push($arrSql1, '(%s,%s,%s,%s)');
				array_push($arrValues1, 2);
				array_push($arrValues1, $goodsId);
				array_push($arrValues1, $val);
				array_push($arrValues1, $key);
			}
			if($arrSql1 && $arrValues1){
				$sql1 .= implode(',', $arrSql1);
				$this->query($sql1, $arrValues1);
			}
		}
	}
	
	public function changeFlag($goodsId,$flag){
		$sql = 'update cms_goods set Flag = %s where GoodsID=%s';
		$this->query($sql,array($flag,$goodsId));
	}
}